//service loding address
import {
    getArg,
    setLocalData,
    getLocalData,
    getRegions
} from '../../mod/tools/tools';

var _ = require('lodash/function');
//获取 区域信息
function initPicker(cb) {
    let address = getLocalData('address');  
    if(!!address) {
        address = JSON.parse(address);
        $.smConfig.rawCitiesData = address;
        init();
        cb && cb();
    } else {
        console.log('xixi');
        getRegions(function(res){
            if (res.status == 1) {
                address = res.data;
                setLocalData('address', JSON.stringify(address));
                //初始化 省市区
                $.smConfig.rawCitiesData = address;
                init();
                cb && cb(res);
            } 
        })
    }

};


//  function getAddressId() {
//     var names = $('.address').text().split(' ');
//     var ids = [];
//     address.forEach(val => {
//         if (val.name == names[0]) {
//             ids.push(val.id);
//             val.child.forEach(val => {
//                 if (val.name == names[1]) {
//                     ids.push(val.id);
//                     val.child.forEach(val => {
//                         if (val.name == names[2]) {
//                             ids.push(val.id);
//                         }
//                     })
//                 }
//             });
//         }
//     })
//     console.log(ids);
//     $('#address').attr('data-id', ids.join(' '));
//     return ids;
// }

    function init() {
        "use strict";
        var format = function (data) {
            var result = [];
            for (var i = 0; i < data.length; i++) {
                var d = data[i];
                if (d.name === "请选择") continue;
                result.push(d.name);
            }
            if (result.length) return result;
            return [""];
        };

        var child = function (data) {
            if (!data.child) return [""];
            return format(data.child);
        };

        var getCities = function (d) {
            for (var i = 0; i < raw.length; i++) {
                if (raw[i].name === d) return child(raw[i]);
            }
            return [""];
        };

        var getDistricts = function (p, c) {
            for (var i = 0; i < raw.length; i++) {
                if (raw[i].name === p) {
                    for (var j = 0; j < raw[i].child.length; j++) {
                        if (raw[i].child[j].name === c) {
                            return child(raw[i].child[j]);
                        }
                    }
                }
            }
            return [""];
        };

        var raw = $.smConfig.rawCitiesData;
        var provinces = raw.map(function (d) {
            return d.name;
        });
        var initCities = child(raw[0]);
        var initDistricts = [""];

        var currentProvince = provinces[0];
        var currentCity = initCities[0];
        var currentDistrict = initDistricts[0];

        var t;
        var defaults = {

            cssClass: "city-picker",
            rotateEffect: false, //为了性能

            onChange: function (picker, values, displayValues) {
                var newProvince = picker.cols[0].value;
                var newCity;
                if (newProvince !== currentProvince) {
                    // 如果Province变化，节流以提高reRender性能
                    clearTimeout(t);

                    t = setTimeout(function () {
                        var newCities = getCities(newProvince);
                        newCity = newCities[0];
                        var newDistricts = getDistricts(newProvince, newCity);
                        picker.cols[1].replaceValues(newCities);
                        picker.cols[2].replaceValues(newDistricts);
                        currentProvince = newProvince;
                        currentCity = newCity;
                        picker.updateValue();
                    }, 200);
                    return;
                }
                newCity = picker.cols[1].value;
                if (newCity !== currentCity) {
                    picker.cols[2].replaceValues(getDistricts(newProvince, newCity));
                    currentCity = newCity;
                    picker.updateValue();
                }
            },

            cols: [{
                    textAlign: 'center',
                    values: provinces,
                    cssClass: "col-province"
                },
                {
                    textAlign: 'center',
                    values: initCities,
                    cssClass: "col-city"
                },
                {
                    textAlign: 'center',
                    values: initDistricts,
                    cssClass: "col-district"
                }
            ]
        };

        $.fn.cityPicker = function (params) {
            return this.each(function () {
                if (!this) return;
                var p = $.extend(defaults, params);
                //计算value
                if (p.value) {
                    $(this).val(p.value.join(' '));
                } else {
                    var val = $(this).val();
                    val && (p.value = val.split(' '));
                }

                if (p.value) {
                    //p.value = val.split(" ");
                    if (p.value[0]) {
                        currentProvince = p.value[0];
                        p.cols[1].values = getCities(p.value[0]);
                    }
                    if (p.value[1]) {
                        currentCity = p.value[1];
                        p.cols[2].values = getDistricts(p.value[0], p.value[1]);
                    } else {
                        p.cols[2].values = getDistricts(p.value[0], p.cols[1].values[0]);
                    }!p.value[2] && (p.value[2] = '');
                    currentDistrict = p.value[2];
                }

                $(this).picker(p);
            });
        };

    };

    export { initPicker }
/*!
 * =====================================================
 * SUI Mobile - http://m.sui.taobao.org/
 *
 * =====================================================
 */


/* jshint unused:false*/